﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.IO.Ports;
using System.Xml;//XML
using System.Xml.Serialization;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Imaging;
using System.ComponentModel;
using System.Reflection;
using System.Net;
using System.Net.Sockets;

namespace YJYpublicClass
{
    class FileOperation
    {
        public static bool SaveData(string filePath, string fnodename, string cnodename, string cnodetext)
        {
            bool booladddata = true;
            XmlDocument xml = new XmlDocument();
            XmlDeclaration xmldel;
            XmlNode root;
            XmlNode node1;
            XmlNode node2;
            if (!File.Exists(filePath))
            {
                xmldel = xml.CreateXmlDeclaration("1.0", null, null);
                xml.AppendChild(xmldel);
                root = xml.CreateElement("Parameter");
                xml.AppendChild(root);
            }
            else
            {
                xml.Load(filePath);
                root = xml.SelectSingleNode("Parameter");
                if (root == null)
                {
                    File.Delete(filePath);
                    booladddata = false;
                    return booladddata;
                }
            }

            if (root.SelectSingleNode(fnodename) != null)
            {
                node1 = root.SelectSingleNode(fnodename);
                if (node1.SelectSingleNode(cnodename) != null)
                {
                    node2 = node1.SelectSingleNode(cnodename);
                    node2.InnerText = cnodetext;
                }
                else
                {
                    node2 = xml.CreateNode(XmlNodeType.Element, cnodename, null);
                    node2.InnerText = cnodetext;
                    node1.AppendChild(node2);
                }
            }
            else
            {
                node1 = xml.CreateNode(XmlNodeType.Element, fnodename, null);
                root.AppendChild(node1);
                node2 = xml.CreateNode(XmlNodeType.Element, cnodename, null);
                node2.InnerText = cnodetext;
                node1.AppendChild(node2);
            }
            xml.Save(filePath);
            return booladddata;
        }

        public static bool ReadData(string filePath, string fnodename, string cnodename, ref string cnodetext)
        {
            if (!File.Exists(filePath))
            {
                cnodetext = "0";
                return false;
            }

            bool boolreaddata = true;
            XmlDocument xml = new XmlDocument();
            xml.Load(filePath);
            XmlNode node1;
            XmlNode node2;
            XmlNode root = xml.SelectSingleNode("Parameter");
            if (root == null)
            {
                boolreaddata = false;
                return boolreaddata;
            }
            if (root.SelectSingleNode(fnodename) != null)
            {
                node1 = root.SelectSingleNode(fnodename);
                if (node1.SelectSingleNode(cnodename) != null)
                {
                    node2 = node1.SelectSingleNode(cnodename);
                    if (node2.InnerText != "")
                    {
                        cnodetext = node2.InnerText;
                    }
                    else
                    {
                        cnodetext = "0";
                    }
                }
                else
                {
                    cnodetext = "0";
                    boolreaddata = false;
                }
            }
            else
            {
                cnodetext = "0";
                boolreaddata = false;
            }
            return boolreaddata;
        }

        public static List<string> GetfileNames(string Folderpath)
        {
            string filePath = Folderpath;
            List<string> resName = new List<string>();
            string[] names = Directory.GetFiles(filePath, "*.xml").Select(path => Path.GetFileName(path)).ToArray();
            for (int i = 0; i < names.Count(); i++)
            {
                names[i] = names[i].Replace(".xml", "");
                //if (names[i] != FSParamer.machineSettingsFilePath)
                resName.Add(names[i]);
            }
            return resName;
        }

        public static string ExtractFileName(string FilePath)
        {
            return Path.GetFileNameWithoutExtension(FilePath);
        }

    }
    public static class XmlHelper
    {
        public static void CreateDirectoryEx(string Path)
        {
            int nPos;
            string PathTemp;
            nPos = Path.LastIndexOf('\\');
            if (nPos < 0)
                nPos = Path.LastIndexOf('/');

            if (nPos < 0)
            {
                return;
            }
            nPos = Path.LastIndexOf('\\');
            if (nPos > -1)
            {
                PathTemp = Path.Substring(0, nPos);
            }
            else
            {
                nPos = Path.LastIndexOf('/');
                PathTemp = Path.Substring(0, nPos);
            }

            Directory.CreateDirectory(PathTemp);

        }
        public static string SaveXML(string strParamFile, object obj)
        {
            try
            {
                if (!File.Exists(strParamFile))
                {
                    CreateDirectoryEx(strParamFile);
                }
                string xml = XmlSerialize(obj, Encoding.UTF8);
                XmlSerializeToFile(obj, strParamFile, Encoding.UTF8);
                return "";
            }
            catch (Exception e)
            {
                return e.Message;
            }
        }
        public static T LoadXML<T>(string strParamFile)
        {
            try
            {
                if (!File.Exists(strParamFile))
                {
                    return default(T);
                }
                return XmlDeserializeFromFile<T>(strParamFile, Encoding.UTF8);
            }
            catch (Exception ex)
            {
                return default(T);
            }
        }
        private static void XmlSerializeInternal(Stream stream, object o, Encoding encoding)
        {
            if (o == null)
                throw new ArgumentNullException("o");
            if (encoding == null)
                throw new ArgumentNullException("encoding");

            XmlSerializer serializer = new XmlSerializer(o.GetType());

            XmlWriterSettings settings = new XmlWriterSettings();
            settings.Indent = true;
            settings.NewLineChars = "\r\n";
            settings.Encoding = encoding;
            settings.IndentChars = "    ";

            using (XmlWriter writer = XmlWriter.Create(stream, settings))
            {
                serializer.Serialize(writer, o);
                writer.Close();
            }
        }

        /// <summary>
        /// 将一个对象序列化为XML字符串
        /// </summary>
        /// <param name="o">要序列化的对象</param>
        /// <param name="encoding">编码方式</param>
        /// <returns>序列化产生的XML字符串</returns>
        public static string XmlSerialize(object o, Encoding encoding)
        {
            using (MemoryStream stream = new MemoryStream())
            {
                XmlSerializeInternal(stream, o, encoding);

                stream.Position = 0;
                using (StreamReader reader = new StreamReader(stream, encoding))
                {
                    return reader.ReadToEnd();
                }
            }
        }

        /// <summary>
        /// 将一个对象按XML序列化的方式写入到一个文件
        /// </summary>
        /// <param name="o">要序列化的对象</param>
        /// <param name="path">保存文件路径</param>
        /// <param name="encoding">编码方式</param>
        public static void XmlSerializeToFile(object o, string path, Encoding encoding)
        {
            if (string.IsNullOrEmpty(path))
                throw new ArgumentNullException("path");

            using (FileStream file = new FileStream(path, FileMode.Create, FileAccess.Write))
            {
                XmlSerializeInternal(file, o, encoding);
            }
        }

        /// <summary>
        /// 从XML字符串中反序列化对象
        /// </summary>
        /// <typeparam name="T">结果对象类型</typeparam>
        /// <param name="s">包含对象的XML字符串</param>
        /// <param name="encoding">编码方式</param>
        /// <returns>反序列化得到的对象</returns>
        public static T XmlDeserialize<T>(string s, Encoding encoding)
        {
            if (string.IsNullOrEmpty(s))
                throw new ArgumentNullException("s");
            if (encoding == null)
                throw new ArgumentNullException("encoding");

            XmlSerializer mySerializer = new XmlSerializer(typeof(T));
            using (MemoryStream ms = new MemoryStream(encoding.GetBytes(s)))
            {
                using (StreamReader sr = new StreamReader(ms, encoding))
                {
                    return (T)mySerializer.Deserialize(sr);
                }
            }
        }
        /// <summary>
        /// 读入一个文件，并按XML的方式反序列化对象。
        /// </summary>
        /// <typeparam name="T">结果对象类型</typeparam>
        /// <param name="path">文件路径</param>
        /// <param name="encoding">编码方式</param>
        /// <returns>反序列化得到的对象</returns>
        public static T XmlDeserializeFromFile<T>(string path, Encoding encoding)
        {
            if (string.IsNullOrEmpty(path))
                throw new ArgumentNullException("path");
            if (encoding == null)
                throw new ArgumentNullException("encoding");

            string xml = File.ReadAllText(path, encoding);
            return XmlDeserialize<T>(xml, encoding);
        }
    }
    public class Helper
    {
        public static List<string> GetAllEnumDescription(Type enumType)//20171216
        {
            List<string> myDes = new List<string>();

            var names = Enum.GetNames(enumType);
            foreach (var name in names)
            {
                var field = enumType.GetField(name);
                var fds = field.GetCustomAttributes(typeof(DescriptionAttribute), true);
                foreach (DescriptionAttribute fd in fds)
                {
                    myDes.Add(fd.Description);
                }
            }
            return myDes;
        }

        public static List<int> GetAllEnumIntValue(Type enumType)//20171216
        {
            List<int> myVal = new List<int>();

            var vals = Enum.GetValues(enumType);
            foreach (var val in vals)
            {
                myVal.Add((int)val);
            }
            return myVal;
        }

        public static string GetEnumDescription(Enum value)
        {
            FieldInfo fi = value.GetType().GetField(value.ToString());

            DescriptionAttribute[] attributes =
            (DescriptionAttribute[])fi.GetCustomAttributes(
            typeof(DescriptionAttribute),
            false);

            if (attributes != null &&
                attributes.Length > 0)
                return attributes[0].Description;
            else
                return value.ToString();
        }


        public static double GetDegreeFromRadian(double radian)
        {
            return 180d * radian / Math.PI;
        }

        public static void ApplyRotation(ref System.Drawing.PointF pt, float angle, System.Drawing.PointF center)
        {
            float scale = 1;
            double tempX = pt.X - center.X;
            double tempY = pt.Y - center.Y;
            pt.X -= center.X;
            pt.Y -= center.Y;

            double cosf = Math.Cos(angle);
            double sinf = Math.Sin(angle);

            pt.X = (float)((tempX * cosf) - (tempY * sinf));
            pt.X *= scale;

            pt.Y = (float)((tempY * cosf) + (tempX * sinf));
            pt.Y *= scale;

            pt.Y += center.Y;
            pt.X += center.X;
        }

        public static double GetRadianFromDegree(double deg)
        {
            return Math.PI * deg / 180d;
        }

        public static List<string> GetAllComPortNumber()
        {
            List<string> comPortNum = new List<string>();

            string[] availablePorts = new string[] { };
            availablePorts = SerialPort.GetPortNames();

            if (availablePorts.Length <= 0) return comPortNum;

            //int num = 0; string numStr = "";
            for (int i = 0; i < availablePorts.Length; i++)
            {
                comPortNum.Add(availablePorts[i]);
                //numStr = availablePorts[i].ToUpper().Replace("COM", "");
                //if (int.TryParse(numStr, out num))
                //    comPortNum.Add(num);
            }

            return comPortNum;
        }

        public static string LocalIPAddress()
        {
            if (!System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable())
            {
                return null;
            }

            IPHostEntry host = Dns.GetHostEntry(Dns.GetHostName());

            return host
                .AddressList
                .FirstOrDefault(ip => ip.AddressFamily == AddressFamily.InterNetwork).ToString();
        }
        public static bool IsProcessOpen(string name)
        {
            //here we're going to get a list of all running processes on
            //the computer
            Process[] podd = Process.GetProcesses();
            foreach (Process clsProcess in Process.GetProcesses())
            {
                //now we're going to see if any of the running processes
                //match the currently running processes. Be sure to not
                //add the .exe to the name you provide, i.e: NOTEPAD,
                //not NOTEPAD.EXE or false is always returned even if
                //notepad is running.
                //Remember, if you have the process running more than once, 
                //say IE open 4 times the loop thr way it is now will close all 4,
                //if you want it to just close the first one it finds
                //then add a return; after the Kill
                if (clsProcess.ProcessName.Contains(name))
                {
                    //if the process is found to be running then we
                    //return a true
                    return true;
                }
            }
            //otherwise we return a false
            return false;
        }
        public static void DeleteFile(string file)
        {
            //去除文件夹和子文件的只读属性
            //去除文件夹的只读属性
            System.IO.DirectoryInfo fileInfo = new DirectoryInfo(file);
            fileInfo.Attributes = FileAttributes.Normal & FileAttributes.Directory;
            //去除文件的只读属性
            System.IO.File.SetAttributes(file, System.IO.FileAttributes.Normal);
            //判断文件夹是否还存在
            if (Directory.Exists(file))
            {
                foreach (string f in Directory.GetFileSystemEntries(file))
                {
                    if (File.Exists(f))
                    {
                        //如果有子文件删除文件
                        File.Delete(f);
                    }
                    else
                    {
                        //循环递归删除子文件夹 
                        DeleteFile(f);
                    }
                }
                //删除空文件夹 
                Directory.Delete(file);
            }
        }
        public static Image ScaleImage(Image image, int maxWidth, int maxHeight)
        {
            var ratioX = (double)maxWidth / image.Width;
            var ratioY = (double)maxHeight / image.Height;
            var ratio = Math.Min(ratioX, ratioY);

            var newWidth = (int)(image.Width * ratio);
            var newHeight = (int)(image.Height * ratio);

            var newImage = new Bitmap(newWidth, newHeight);

            using (var graphics = Graphics.FromImage(newImage))
                graphics.DrawImage(image, 0, 0, newWidth, newHeight);

            return newImage;
        }

        public static Bitmap MakeGrayscale(Bitmap original)
        {
            //create a blank bitmap the same size as original
            Bitmap newBitmap = new Bitmap(original.Width, original.Height);

            //get a graphics object from the new image
            Graphics g = Graphics.FromImage(newBitmap);

            //create the grayscale ColorMatrix
            ColorMatrix colorMatrix = new ColorMatrix(
               new float[][]
      {
         new float[] {.3f, .3f, .3f, 0, 0},
         new float[] {.59f, .59f, .59f, 0, 0},
         new float[] {.11f, .11f, .11f, 0, 0},
         new float[] {0, 0, 0, 1, 0},
         new float[] {0, 0, 0, 0, 1}
      });

            //create some image attributes
            ImageAttributes attributes = new ImageAttributes();

            //set the color matrix attribute
            attributes.SetColorMatrix(colorMatrix);

            //draw the original image on the new image
            //using the grayscale color matrix
            g.DrawImage(original, new Rectangle(0, 0, original.Width, original.Height),
               0, 0, original.Width, original.Height, GraphicsUnit.Pixel, attributes);

            //dispose the Graphics object
            g.Dispose();
            return newBitmap;
        }
       

        public static void CreateDirectoryEx(string Path)
        {
            int nPos;
            string PathTemp;
            nPos = Path.LastIndexOf('\\');
            if (nPos < 0)
                nPos = Path.LastIndexOf('/');

            if (nPos < 0)
            {
                return;
            }
            nPos = Path.LastIndexOf('\\');
            if (nPos > -1)
            {
                PathTemp = Path.Substring(0, nPos);
            }
            else
            {
                nPos = Path.LastIndexOf('/');
                PathTemp = Path.Substring(0, nPos);
            }

            Directory.CreateDirectory(PathTemp);

        }
      

        public static void SetDoubleBuffered(System.Windows.Forms.Control c)
        {
            //请参考下面的博客
            //http://blogs.msdn.com/oldnewthing/archive/2006/01/03/508694.aspx
            if (System.Windows.Forms.SystemInformation.TerminalServerSession)
                return;

            System.Reflection.PropertyInfo aProp =
                  typeof(System.Windows.Forms.Control).GetProperty(
                        "DoubleBuffered",
                        System.Reflection.BindingFlags.NonPublic |
                        System.Reflection.BindingFlags.Instance);

            aProp.SetValue(c, true, null);
        }
        public static Process GetSystemProcess(string name)
        {
            //here we're going to get a list of all running processes on
            //the computer
            foreach (Process clsProcess in Process.GetProcesses())
            {
                //now we're going to see if any of the running processes
                //match the currently running processes. Be sure to not
                //add the .exe to the name you provide, i.e: NOTEPAD,
                //not NOTEPAD.EXE or false is always returned even if
                //notepad is running.
                //Remember, if you have the process running more than once, 
                //say IE open 4 times the loop thr way it is now will close all 4,
                //if you want it to just close the first one it finds
                //then add a return; after the Kill
                if (clsProcess.ProcessName.Contains(name))
                {
                    //if the process is found to be running then we
                    //return a true
                    return clsProcess;
                }
            }
            //otherwise we return a false
            return null;
        }

        public static bool CheckApplicationRunning()
        {
            return System.Diagnostics.Process.GetProcessesByName(System.IO.Path.GetFileNameWithoutExtension(System.Reflection.Assembly.GetEntryAssembly().Location)).Count() > 1;
        }


    }
    
}
